package com.dsai.dsai.controller;


import com.dsai.dsai.repository.ChatHistoryRespository;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;

/**
 * @author Administrator
 */
@RestController
@RequestMapping("/api/ai")
public class ChatController {

    private  final ChatClient chatClient;
    private  final ChatHistoryRespository  chatHistoryRespository;
    // 手动编写构造器
    public ChatController(ChatClient chatClient, ChatHistoryRespository chatHistoryRespository) {
        this.chatClient = chatClient;
        this.chatHistoryRespository = chatHistoryRespository;
    }

    @RequestMapping(value = "/chat", produces = "text/html;charset=UTF-8")
    public Flux<String> chat(String prompt,String chatId) {
        //1、保存会话ID
        chatHistoryRespository.save("chat", chatId);
        //2、请求模型
        return chatClient.prompt()
                .user(prompt)
                //传递会话ID，不同的会话ID，会话记忆会不同
                .advisors(a -> a.param(CHAT_MEMORY_CONVERSATION_ID_KEY,chatId))
                .stream()
                .content();
    }
}
